package com.zc.trendsDispatch.task;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.zc.common.constant.RedisKeyConstants;
import com.zc.iotDevice.domain.ChargeStationPort;
import com.zc.iotDevice.mapper.ChargeStationPortMapper;
import com.zc.manager.device.domain.IotDevice;
import com.zc.manager.device.entity.DeviceProperty;
import com.zc.manager.device.mapper.IotDeviceMapper;
import com.zc.manager.device.service.IIotDeviceService;
import com.zc.operator.domain.ChargeStation;
import com.zc.operator.mapper.ChargeStationMapper;
import com.zc.remoteControl.service.RemoteInstructSendService;
import com.zc.trendsDispatch.domain.ChargeStationRealPowerHis;
import com.zc.trendsDispatch.domain.ChargeStationStrategy;
import com.zc.trendsDispatch.domain.ChargeStationStrategyAssociation;
import com.zc.trendsDispatch.mapper.ChargeStationRealPowerHisMapper;
import com.zc.trendsDispatch.mapper.ChargeStationStrategyAssociationMapper;
import com.zc.trendsDispatch.mapper.ChargeStationStrategyMapper;
import com.zc.util.ArithmeticUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.zc.trendsDispatch.task.ChargeStationStrategyTask.Validation;
import static com.zc.util.ModbusCRC16.calculateCRC;
import static com.zc.util.RadixUtil.hexToByte;
import static com.zc.util.RadixUtil.intHECToHex;

@Component("stationRealPowerCountTask")
public class StationRealPowerCountTask {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ChargeStationMapper chargeStationMapper;

    @Resource
    private ChargeStationPortMapper chargeStationPortMapper;

    @Resource
    private RemoteInstructSendService remoteInstructSendService;

    @Resource
    private ChargeStationRealPowerHisMapper chargeStationRealPowerHisMapper;

    @Resource
    private ChargeStationStrategyAssociationMapper chargeStationStrategyAssociationMapper;

    @Resource
    private ChargeStationStrategyMapper chargeStationStrategyMapper;

    @Resource
    private IotDeviceMapper iotDeviceMapper;

    @Autowired
    private IIotDeviceService iiotDeviceService;//设备

    private static final Logger LOGGER = LoggerFactory.getLogger(StationRealPowerCountTask.class);

    public void stationRealPowerCount(){
        Date nowDate = DateUtils.getNowDate();
        List<ChargeStation> chargeStations = chargeStationMapper.selectChargeStationList(new ChargeStation());
        chargeStations.forEach(station->{
            ChargeStationRealPowerHis chargeStationRealPowerHis=new ChargeStationRealPowerHis();
            chargeStationRealPowerHis.setChargeStationId(station.getChargeStationId());
            chargeStationRealPowerHis.setDeptId(station.getDeptId());
            chargeStationRealPowerHis.setChargeStationCode(station.getChargeStationCode());
            chargeStationRealPowerHis.setChargeStationName(station.getChargeStationName());
            chargeStationRealPowerHis.setOperatorCode(station.getOperatorCode());
            chargeStationRealPowerHis.setOperatorName(station.getOperatorName());
            chargeStationRealPowerHis.setChargeStationStatus(station.getChargeStationStatus());
            chargeStationRealPowerHis.setChargeStationPhoto(station.getChargeStationPhoto());

            ChargeStationStrategyAssociation chargeStationStrategyAssociation=new ChargeStationStrategyAssociation();
            chargeStationStrategyAssociation.setStationId(station.getChargeStationCode());
            List<ChargeStationStrategyAssociation> chargeStationStrategyAssociations = chargeStationStrategyAssociationMapper.selectChargeStationStrategyAssociationList(chargeStationStrategyAssociation);
            //总表功率
            double countPower=0;
            for (int i = 0; i < chargeStationStrategyAssociations.size(); i++) {
                Object cacheMapValue = redisCache.getCacheMapValue(RedisKeyConstants.STATION_DEVICE_REAL_POWER.replaceAll(":station:device", ":"+station.getChargeStationCode()+""), chargeStationStrategyAssociations.get(i).getDeviceId());
                if(cacheMapValue!=null){
                    countPower = ArithmeticUtils.add(countPower, Double.parseDouble(cacheMapValue.toString()));
                }
            }
            ChargeStationStrategy chargeStationStrategy=  new ChargeStationStrategy();
            chargeStationStrategy.setStationCode(station.getChargeStationCode());
            List<ChargeStationStrategy> chargeStationStrategies = chargeStationStrategyMapper.selectChargeStationStrategyList(new ChargeStationStrategy());
            //变压器容量
            int transformerCapacity =0;
            //变压器阈值
            int threshold  =0;
            if(chargeStationStrategies.size()>0){
                transformerCapacity= chargeStationStrategies.get(0).getTransformerCapacity();
                threshold= chargeStationStrategies.get(0).getThreshold();
            }
            //可用阈值（变压器容量-变压器阈值）
            double available = ArithmeticUtils.sub(transformerCapacity, threshold);
            ChargeStationPort chargeStationPort=new ChargeStationPort();
            chargeStationPort.setStationId(station.getChargeStationId());
            //0离线1空闲2使用
            chargeStationPort.setServiceStatus("2");
            //充电桩功率
            AtomicReference<Double> chargeStationRealPower= new AtomicReference<>((double) 0);
            List<ChargeStationPort> listPort = chargeStationPortMapper.getList(chargeStationPort);
            listPort.forEach(port->{
                Map<String, DeviceProperty> realData = remoteInstructSendService.getRealData(port.getId());
                if(realData.containsKey("power")){
                    String power = String.valueOf(realData.get("power").getValue());
                    if(StringUtils.isNotBlank(power)){
                        double now= Double.parseDouble(power);
                        chargeStationRealPower.set(ArithmeticUtils.add(chargeStationRealPower.get(), now));
                    }
                }else {
                    //未获取到设备实时数据不做操作
                }
            });
            //总表功率-充电桩功率=负载功率
            double loadPower = ArithmeticUtils.sub(countPower, chargeStationRealPower.get());
            //实际可用负载（可用阈值-负载功率）
            double reality = ArithmeticUtils.sub(available, loadPower);
            chargeStationRealPowerHis.setStationRealPower(loadPower+"kw");
            chargeStationRealPowerHis.setChargeStationAllocationPower(reality+"kw");
            chargeStationRealPowerHis.setChargeStationRealPower(String.valueOf(chargeStationRealPower)+"kw");
            chargeStationRealPowerHis.setUpdateTime(nowDate);
            redisCache.setCacheMapValue(RedisKeyConstants.STATION_REAL_POWER,station.getChargeStationCode(),chargeStationRealPowerHis);
        });
    }

    public void stationRealPowerStorage(){
        Date nowDate = DateUtils.getNowDate();
        Map<String, ChargeStationRealPowerHis> cacheMap = redisCache.getCacheMap(RedisKeyConstants.STATION_REAL_POWER);
        List<ChargeStationRealPowerHis> listHis=cacheMap.entrySet().stream().map(entry ->entry.getValue()).collect(Collectors.toList());
        listHis.forEach(his->{
            his.setSaveTime(nowDate);
        });
        chargeStationRealPowerHisMapper.batchInsertChargeStationRealPowerHis(listHis);
    }

    public void selectMaxPower(){
        for (IotDevice iotDevice : iotDeviceMapper.selectIotDeviceList()) {
            if("YTSN-CDZ-N01".equals(iotDevice.getProductId())){
                String functionId="sendInstruct";
                String reply="680F000000E1"+iotDevice.getId()+"01010001";
                String crcValidation = Validation(reply);
                reply=reply+crcValidation;
                Map<String, Object> map=new HashMap();
                map.put("message",reply);
                System.err.println("查询的设备："+iotDevice.getId()+"查询的报文："+reply);
                remoteInstructSendService.sendMessage(iotDevice.getId(),functionId,map);
            }
        }



    }




}
